Skip to main content

apply、call、bind 怎么使用?

在 js 中,所有的函数在被调用的时候都会默认传入两个参数,一个是 this,还有一个是 arguments。

当我们需要改变 this 的指向,使函数可以被其他对象来调用,就可以使用 call,apply 和 bind 方法,apply、call、bind 都是改变函数中的 this 值

call,apply,bind 区别

  • call 的 arg 传参需一个一个传,全都用逗号分隔;apply 则直接传一个数组
function hello(name, age) {
console.log(name)
console.log(age)
}
hello.call(this, 'tsrot', 24)
hello.apply(this, ['tsrot', 24])
  • call 和 apply 直接执行函数,而 bind 需要再一次调用
var obj = {
x: 81
}
var foo = {
getX: function () {
return this.x
}
}
console.log(foo.getX.bind(obj)())
console.log(foo.getX.call(obj))
console.log(foo.getX.apply(obj))

call,apply,bind 应用场景

  • 如果不需要关心具体有多少参数被传入函数,选用 apply();
  • 如果确定函数可接收多少个参数,并且想一目了然表达形参和实参的对应关系,用 call();
  • 如果我们想要将来再调用方法,不需立即得到函数返回结果,则使用 bind()
this.num = 9;
var mymodule = {
num: 81,
getNum: function() {
console.log(this.num);
}
};

mymodule.getNum(); // 81

var getNum = mymodule.getNum;
getNum(); // 9, 因为在这个例子中,"this"指向全局对象

var boundGetNum = getNum.bind(mymodule);
boundGetNum(); // 81

参考文章: https://www.runoob.com/w3cnote/js-call-apply-bind.html > https://segmentfault.com/a/1190000022279193